# coding: utf-8
import json

from django.utils.decorators import method_decorator
from django.views.decorators.http import require_GET
from django.views.generic import TemplateView

from common.activity.recharge_red_envelope_db import get_winners_list, get_all_envelope_status, \
    get_activity_recharge_count, open_envelope
from common.utils.api import token_required
from common.utils.decorator import response_wrapper


@require_GET
@response_wrapper
def get_winners(req):
    winners_list = get_winners_list()
    return [_wrap_winner_info(winner_info) for winner_info in winners_list]


def _wrap_winner_info(winner_info):
    info = "恭喜【{}】获得{}元"
    user_name = winner_info.user_name[:1] + "***" + winner_info.user_name[-1:]
    return info.format(user_name, winner_info.amount)


class RedEnvelopeView(TemplateView):
    def get(self, req, *args, **kwargs):
        """
        获得当前用户的红包状态
        """
        user_id = req.user_id
        red_envelope = get_all_envelope_status(user_id)
        today_recharge = get_activity_recharge_count(user_id)
        return dict(red_envelope=red_envelope, today_recharge=today_recharge)

    @method_decorator(token_required)
    def post(self, req):
        """
        开启红包
        """
        param_dct = json.loads(req.body)
        red_envelope_id = int(param_dct.get('red_envelope_id'))
        user_id = req.user_id

        return {'award': open_envelope(user_id, red_envelope_id)}

    @method_decorator(response_wrapper)
    def dispatch(self, *args, **kwargs):
        return super(RedEnvelopeView, self).dispatch(*args, **kwargs)


@require_GET
@response_wrapper
def get_time(request):
    return dict(start_time=1545494400, end_time=1546531200)
